package controller;

import model.Admin;
import model.AdminDao;
import model.User;
import model.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA
 * Description
 * User：chenshu
 * Date：2023-12-24
 * Time：21:41
 */
@WebServlet("/adlogin")
public class AdminLoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf8");
        resp.setContentType("text/html;charset=utf8");
        String adminName = req.getParameter("adminName");
        String password = req.getParameter("password");
        if (adminName == null || password == null || adminName.isEmpty() || password.isEmpty()){
            resp.getWriter().write("您的用户名或密码为空！");
        }
        AdminDao adminDao = new AdminDao();
        Admin admin = adminDao.selectByName(adminName);
        if (admin == null) {
            resp.getWriter().write("你输入的用户名或密码错误！");
            return;
        }
        if (!admin.getPassword().equals(password)) {
            resp.getWriter().write("你输入的用户名或密码错误！");
            return;
        }
        HttpSession session = req.getSession(true);
        session.setAttribute("admin", admin);
        System.out.println("管理员登陆成功");
        resp.sendRedirect("user_list.html");
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession(false);
        if (session == null) {
            resp.setStatus(403);
            return;
        }

        if (session.getAttribute("admin") == null) {
            resp.setStatus(403);
            return;
        }
        resp.setStatus(200);
    }
}
